package com.bawei.login

import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.cache.CacheManager
import com.bawei.cache.CacheStrategy
import com.bawei.cache.cache.KVACache
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.login.databinding.ActivityLoginBinding
import com.bawei.login.entity.UserEntity
import com.bawei.login.viewmodel.LoginViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = "/login/activity")
class LoginActivity: BaseMviActivity<ActivityLoginBinding>() {

    private val mViewModel: LoginViewModel by viewModels()

    private var username: String = ""
    private var password: String = ""

    override fun getLayoutId(): Int = R.layout.activity_login

    override fun initViews() {
        mDataBinding.includedTitle.findViewById<ImageView>(com.bawei.common.R.id.iv_back).setOnClickListener {
            this@LoginActivity.finish()
        }
        var titleView = mDataBinding.includedTitle.findViewById<TextView>(com.bawei.common.R.id.tv_title)
        titleView.visibility = View.VISIBLE
        titleView.text = "登录"
        //添加输入框内容更改事件
        mDataBinding.etAccount.addTextChangedListener{
            username = it.toString()
        }

        mDataBinding.etPassword.addTextChangedListener {
            password = it.toString()
        }
        //登录按钮的点击事件
        mDataBinding.tvLoginBtn.setOnClickListener {
            loginToServer()
        }
    }

    private fun loginToServer(){
        //参数校验
        if(username.isNullOrEmpty() || password.isNullOrEmpty()){
            showToastMessage("账号密码不能为空！")
        }
        //发送请求意图
        lifecycleScope.launch {
           mViewModel.channel.send(LoginViewIntent.LoginToServer(username, password))
        }
    }

    override suspend fun collectUIState() {
        mViewModel.uiState.collect{
            when(it){
                is LoginUiState.LoginToServerSuccess -> saveUserInfo(it.userEntity)
                is LoginUiState.LoginToServerFail -> showToastMessage(it.msg)
                else -> {}
            }
        }
    }

    private fun saveUserInfo(entity: UserEntity){
        //保存登录Token
        if(!entity.token.isNullOrEmpty()){
            CacheManager.getCache(CacheStrategy.MMKV).putString("token", entity.token)
        }
        //保存用户信息
        (CacheManager.getCache(CacheStrategy.ACACHE) as KVACache).putSerializable("userInfo", entity)
        //关闭页面
        this@LoginActivity.finish()
    }



}